package com.notes.action;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.hibernate.Hibernate;
import org.primefaces.component.datalist.DataList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.notes.model.Item;
import com.notes.model.SelectItemData;
import com.notes.model.User;
import com.notes.service.ItemService;
import com.notes.service.UserService;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
@Component(value="itemManageAction")
@SessionScoped
public class ItemManageAction {

	private String text;
	private Long userId;
	private User user;
	private Date remindTime;
	private Date currentTime;
	private String timeReminder;
	@Autowired
	private ItemService itemService;
	@Autowired
	private UserService userService;

	//@ManagedProperty(value="#{loginAction}")
	@Autowired
	private LoginAction loginAction;
	private List<Item> itemSet;	
	private List<SelectItemData> itemList;
	private List<SelectItemData> selectedList;
	private List<SelectItemData> doneItemList;
	


	@PostConstruct
	public void init() {
		itemSet = new ArrayList<Item>();
		selectedList = new ArrayList<SelectItemData>();
	}
	

	public void refresh() {
//		FacesContext context = FacesContext.getCurrentInstance();
//		userId = (Long) context.getExternalContext().getSessionMap().get("userId");
		itemSet = userService.getItemByUserId(loginAction.getUserId());
//		user = userService.getUserByID(loginAction.getUserId());
//		itemSet = user.getItemSet();
		itemList = new ArrayList<SelectItemData>();		
//		Iterator<Item> itr = itemSet.iterator();
//		while(itr.hasNext()) {
//	         Item item = itr.next();
//	         SelectItemData sData = new SelectItemData();
//	         if(item.getCompleteIndicator().equals("N") && item.getDeleteIndicator().equals("N")){
//	        	 sData.setItemId(item.getItemId());
//		         sData.setDate(item.getDate());
//		         sData.setText(item.getText());
//		         itemList.add(sData); 
//	         }
//	        	         
//	      }
//		for(Item item:itemSet){
//			SelectItemData sData = new SelectItemData();			
//			if(item.getCompleteIndicator().equals("N") && item.getDeleteIndicator().equals("N")){
//	        	 sData.setItemId(item.getItemId());
//		         sData.setDate(item.getDate());
//		         sData.setText(item.getText());
//				itemList.add(sData);
//			}
//		}
		for(int i=itemSet.size()-1;i>=0 ;i--){
			SelectItemData sData = new SelectItemData();
			if(itemSet.get(i).getCompleteIndicator().equals("N") &&itemSet.get(i).getDeleteIndicator().equals("N")){
				sData.setItemId(itemSet.get(i).getItemId());
		         sData.setDate(itemSet.get(i).getDate());
		         sData.setText(itemSet.get(i).getText());
		         sData.setRemindTime(itemSet.get(i).getRemindTime());
				itemList.add(sData);
			}
		}
		
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public List<SelectItemData> getItemList() {
		return itemList;
	}

	public void setItemList(List<SelectItemData> itemList) {
		this.itemList = itemList;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}


	public List<SelectItemData> getSelectedList() {
		return selectedList;
	}

	public void setSelectedList(List<SelectItemData> selectedList) {
		this.selectedList = selectedList;
	}


	public String itemAddAction() {
		
		if (text.isEmpty() || calculateMins(new Date(),remindTime)<=0) {	         
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "Invalid input"));
		} else {
			
			itemService.addItem(text, loginAction.getUserId(),remindTime);
			refresh();
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Successful","Add successed"));
		}
		text = null;
		remindTime = null;
		return "webPages/notesEdit";
	}

	private int calculateMins(Date currentTime, Date remindTime) {
		int mins;
		mins = (int) ((remindTime.getTime() - currentTime.getTime())/60000);
		return mins;
	}


	public String itemDoneAction(){
		if(selectedList.isEmpty()){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "please select"));
		}
		else{
			itemService.itemDone(loginAction.getUserId(),selectedList);
			refresh();
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Successful", ""));
		}
		
		return "webPages/notesEdit";
	}
	
	public String itemDeleteAction(){
		if(selectedList.isEmpty()){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "please select"));
		}else{
			itemService.itemDelete(loginAction.getUserId(),selectedList);	
			refresh();
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Successful", ""));			
		}
		return "webPages/notesEdit";	
	}
	

	public String itemHistory(){	
//		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//		System.out.println("is"+auth.getAuthorities());
		itemSet = itemService.itemDoneHistory(loginAction.getUserId());
		doneItemList = new ArrayList<SelectItemData>();
		for(Item item:itemSet){
			SelectItemData sData = new SelectItemData();
			sData.setDate(item.getDate());
			sData.setText(item.getText());
			doneItemList.add(sData);
		}		
		return "notesHistory?faces-redirect=true";
	}

	public String returnToNotesEditAction(){
		refresh();
		return "notesEdit?faces-redirect=true";
		
	}

	public void calculateTime(){

		List<Item> itemList = itemService.getItemListByUserId(loginAction.getUserId());
		currentTime = new Date();
		Iterator<Item> itrItem = itemList.iterator();
		while(itrItem.hasNext()){
			Item item = itrItem.next();
			int leftTime = calculateMins(currentTime,item.getRemindTime());
			if(leftTime==0){
				timeReminder = "It's time!";
			}

		}
	}
	
	
	public LoginAction getLoginAction() {
		return loginAction;
	}

	public void setLoginAction(LoginAction loginAction) {
		this.loginAction = loginAction;
	}


	public ItemService getItemService() {
		return itemService;
	}


	public void setItemService(ItemService itemService) {
		this.itemService = itemService;
	}


	public UserService getUserService() {
		return userService;
	}


	public void setUserService(UserService userService) {
		this.userService = userService;
	}


	public List<Item> getItemSet() {
		return itemSet;
	}


	public void setItemSet(List<Item> itemSet) {
		this.itemSet = itemSet;
	}


	public List<SelectItemData> getDoneItemList() {
		return doneItemList;
	}


	public void setDoneItemList(List<SelectItemData> doneItemList) {
		this.doneItemList = doneItemList;
	}


	public Date getRemindTime() {
		return remindTime;
	}


	public void setRemindTime(Date remindTime) {
		this.remindTime = remindTime;
	}


	public Date getCurrentTime() {
		return currentTime;
	}


	public void setCurrentTime(Date currentTime) {
		this.currentTime = currentTime;
	}


	public String getTimeReminder() {
		return timeReminder;
	}


	public void setTimeReminder(String timeReminder) {
		this.timeReminder = timeReminder;
	}
}
